package com.licheedev.silentinstall

import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import com.licheedev.context.AppProvider
import java.io.File

/**
 * apk信息
 */
class ApkInfo : Comparable<ApkInfo> {
    val path: String
    val pkgInfo: PackageInfo?

    val packageName: String get() = pkgInfo?.packageName ?: "unknown_package"
    val versionName: String get() = pkgInfo?.versionName ?: "unknown_version"
    val versionCode: Int get() = pkgInfo?.versionCode ?: -1

    constructor(path: String) {
        this.path = path
        var pkgInfo: PackageInfo? = null
        try {
            pkgInfo =
                packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        this.pkgInfo = pkgInfo
    }

    constructor(file: File) : this(file.absolutePath)


    override fun compareTo(o: ApkInfo): Int {
        return versionCode - o.versionCode
    }

    override fun toString(): String {
        return ("ApkInfo{"
                + "path='"
                + path
                + '\''
                + ", packageName='"
                + packageName
                + '\''
                + ", versionName='"
                + versionName
                + '\''
                + ", versionCode="
                + versionCode
                + '}')
    }

    companion object {

        private val packageManager: PackageManager get() = AppProvider.application.packageManager

        /** 反过来的比较器 */
        @JvmStatic
        val REVERSE_COMPARATOR = java.util.Comparator<ApkInfo> { o1, o2 -> -o1.compareTo(o2) }

        /** 当前app的包名 */
        @JvmStatic
        val thisPackageName: String
            get() = AppProvider.application.packageName

        /** 当前app的版本名 */
        @JvmStatic
        val thisVersionName: String
            get() = try {
                val info: PackageInfo = packageManager.getPackageInfo(thisPackageName, 0)
                info.versionName
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                "unknown_package"
            }

        /** 当前app的版本号 */
        @JvmStatic
        val thisVersionCode: Int
            get() = try {
                val info: PackageInfo = packageManager.getPackageInfo(thisPackageName, 0)
                info.versionCode
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                -1
            }


    }
}